const Friend = require('../../model/friend')

// 判断是否是好友
exports.isFriend = async (uid, fid) => {

  try {
    var user = await Friend.find({ userId: uid,friendId: fid , state: 0 })
  } catch (error) {
    return error
  }
  if(user.length>0){
    return true
  }else{
    return false
  }
}
//获取所有好友
exports.getFriend = async (uid, res) => {
  try {
    var user = await Friend.find({ userId: uid , state: 0 }).populate({
      path: 'friendId',
      select:{_id:1,name:1,avatar:1,email:1,explain:1}
    })
  } catch (error) {
    return res.send({
      status: 500
    })
  }
  // console.log(user);
  var data = []
  user.forEach(item=>{
    data.push({_id:item.friendId._id,name:item.friendId.name,email:item.friendId.email,avatar:item.friendId.avatar,time:item.time})
  })
  res.send({
    status: 200,
    data
  })
}
//分页获取好友，page页码 pagesize 每页个数
exports.getFriendPager = async (uid, page, pagesize, res) => {
  try {
    var skip = (page - 1) * pagesize
    var total = Friend.find({ userId: uid }, { state: 0 }).count()
    var data = Friend.find({ userId: uid }, { state: 0 }).skip(skip).limit(pagesize)
  } catch (error) {
    return res.send({
      status: 500
    })
  }
  res.send({
    status: 200,
    data
  })
}
// 新加好友
exports.createFriend = async (uid,fid,msg,res)=>{
  try {
    var data = await Friend.findOne({userId:uid,friendId:fid})
    if(data){
     return res.send({
      status:200
    })
    }
    await Friend.create({userId:uid,friendId:fid,state:2})
    await Friend.create({userId:fid,friendId:uid,state:1,message:msg})
  } catch (err) {
    return res.send({
      status:400
    })
  }
  res.send({
    status:200
  })
}

exports.getnewFriend=async (id,res)=>{
  try {
    var user = await Friend.find({userId:id,state:1}).populate({path:'friendId',select:'_id name avatar'}).select('friendId message time').sort({time:-1})
  } catch (error) {
    return res.send({
      status:400
    })
  }
  var data = [] 
  user.forEach(item=>{
    data.push({name:item.friendId.name,avatar:item.friendId.avatar,message:item.message,time:item.time,id:item.friendId._id})
  })
  res.send({
    status:200,
    data
  })
}

exports.pass = async (uid,fid,res)=>{
  console.log(uid,fid);
  try {
     await Friend.updateMany({$or:[{userId:uid,friendId:fid},{userId:fid,friendId:uid}]},{state:0})
  } catch (error) {
    return res.send({
      status:400
    })
  }
  res.send({
    status:200
  })
}

exports.refuse = async (uid,fid,res)=>{
  try {
    await await Friend.deleteMany({$or:[{userId:uid,friendId:fid},{userId:fid,friendId:uid}]})
  } catch (error) {
    return res.send({
      status:400
    })
  }
  res.send({
    status:200
  })
}